<!--
 * @Author       : Hejh(3010733382@qq.com)
 * @Version      : V1.0
 * @Date         : 2024-02-21 11:29:23
 * @Description  : 添加或者更新文档角色
-->

<template>
  <div class="bg-lightColor auth-edit-con p-3 text-[13px]" v-loading="loading">
    <n-grid x-gap="12" :cols="1" class="mb-2">
      <n-gi>
        <n-button
          type="primary"
          size="small"
          class="!text-[13px]"
          @click="backView"
        >
          <div class="mr-2 rotate-90 transform">
            <SvgIcon icon="xiala" color="#fff" size="10px"></SvgIcon>
          </div>
          返回
        </n-button>
      </n-gi>
    </n-grid>
    <n-divider class="!my-2" />

    <n-form
      ref="authFormRef"
      :label-width="isSmall ? 100 : 120"
      label-placement="left"
      :label-align="isSmall ? 'left' : 'right'"
      :model="auth"
      size="small"
      require-mark-placement="left"
      :rules="formRule"
    >
      <n-form-item label="名称：" path="name">
        <n-input
          class="!w-[300px]"
          v-model:value="auth.name"
          :allow-input="noSideSpace"
          placeholder="请输入文档角色名称"
          clearable
          :maxlength="25"
        />
        <color-select v-model:color="auth.label"></color-select>
      </n-form-item>
      <n-form-item label="是否显示：" path="isVisible">
        <n-switch
          v-model:value="auth.isVisible"
          :checked-value="1"
          :unchecked-value="0"
        />
        <div class="ml-[12px] text-gray-400 text-[12px]">
          设置部门文档角色时是否显示该角色
        </div>
      </n-form-item>

      <n-divider class="!my-2" />
      <n-alert
        :show-icon="false"
        type="warning"
        class="mb-2 !text-[13px]"
        v-if="authRes && authRes.system === 1"
      >
        提示：系统默认内置文档角色，不支持修改。您可以创建新的文档角色
      </n-alert>
      <n-form-item label="权限：" path="permissionIds">
        <n-checkbox-group
          v-model:value="auth.permissionIds"
          :disabled="authRes && authRes.system === 1"
        >
          <n-space item-style="display: block;" vertical>
            <n-checkbox
              :value="item.id"
              :label="item.name"
              v-for="item in permissions"
              :key="item.id"
            />
          </n-space>
        </n-checkbox-group>
      </n-form-item>
      <n-form-item label=" ">
        <n-checkbox
          v-model:checked="allSelect"
          class="w-full"
          :disabled="authRes && authRes.system === 1"
        >
          全选/取消
        </n-checkbox>
      </n-form-item>
      <n-form-item label=" " v-permission="[PERMISSIONS.AUTH_EDIT]">
        <n-button
          type="primary"
          class="grent-btn w-[120px]"
          @click="handleSave"
        >
          保存
        </n-button>
      </n-form-item>
    </n-form>
  </div>
</template>

<script setup lang="ts">
import type { FormInst } from 'naive-ui'
import { getPermissionByPage } from '@/api/permission'
import type { RoleRes, RoleUpdateReq } from '@/types/role'
import { noSideSpace } from '@/utils'
import { PERMISSIONS } from '@/constants/permission'
import { userMenuShow } from '@/hooks/useMenuShow'
import ColorSelect from '@/views/Admin/components/ColorSelect.vue'
import type { IndexObj } from '@/types/commom'

const { isSmall } = userMenuShow()

const props = defineProps<{
  isModify: boolean
  authRes?: RoleRes
}>()

const emits = defineEmits<{
  (e: 'backView'): void
  (e: 'changeAuth', type: number, data: RoleUpdateReq): void
}>()
const backView = () => {
  emits('backView')
}

const auth = reactive<RoleUpdateReq>({
  name: '',
  desc: '',
  label: '#108EE9',
  isVisible: 1,
  permissionIds: []
})

const allSelect = computed({
  get: () => {
    return permissions.value.length === auth.permissionIds.length
  },
  set: (value) => {
    if (value) {
      auth.permissionIds = permissions.value.map((item) => item.id)
    } else {
      auth.permissionIds = []
    }
  }
})

const loading = ref(false)

const permissions = ref<IndexObj[]>([])
const loadDocPermissions = async () => {
  loading.value = true
  await getPermissionByPage({
    page: 1,
    pageSize: 999,
    type: 1
  })
    .then((res) => {
      permissions.value = res.data.items
    })
    .catch(console.error)
    .finally(() => {
      loading.value = false
    })
}

const formRule = {
  name: [
    {
      required: true,
      message: '请输入文档角色名称',
      trigger: ['blur']
    },
    {
      min: 1,
      max: 50,
      trigger: ['blur'],
      message: '长度在1-50位'
    }
  ]
}

const authFormRef = ref<FormInst | null>(null)

const initAuth = () => {
  if (props.isModify) {
    const { name, desc, label, isVisible, Permissions, id } =
      props.authRes as RoleRes
    auth.roleId = id
    auth.name = name
    auth.desc = desc
    auth.label = label
    auth.isVisible = isVisible
    auth.permissionIds = Permissions.map((item) => item.id)
  }
}

onMounted(async () => {
  await loadDocPermissions()
  initAuth()
})

const handleSave = () => {
  authFormRef.value?.validate((error: any) => {
    if (error) {
      return
    }
    if (props.isModify) {
      emits('changeAuth', 1, auth)
    } else {
      emits('changeAuth', 0, auth)
    }
  })
}
</script>

<style scoped lang="scss"></style>
